#include <string.h>
#include <jni.h>
#include <stdio.h>
#include <android/log.h>
#include "gigabase/gigabase.h"

namespace AFcoder {
	namespace JNI {
		inline bool regJNI(JNIEnv *env, const char *clazz, JNINativeMethod* methods, int count) {
			jclass c = env->FindClass(clazz);
			return c && env->RegisterNatives(c, &methods[0], 1)>=0;
		}

		/**
		 * 系统定义: jint JNI_OnLoad(JavaVM *vm, void *reserved);
		 * @param jni_version JNI_VERSION_X_X
		 */
		template <class T>
		inline jint JNI_OnLoad(JavaVM *vm, jint jni_version, T call_back) {
			JNIEnv *env = NULL;
			if( vm->GetEnv((void**) &env, jni_version) != JNI_OK )
				return -1;

			return call_back(env) ? jni_version : -1;
		}
	}
}


void d(const char *str) {
	__android_log_print(ANDROID_LOG_DEBUG, "AFcoderN", "%s", str);
}

void d(int n) {
	__android_log_print(ANDROID_LOG_DEBUG, "AFcoderN", "%d", n);
}

struct test {
    int n;

    TYPE_DESCRIPTOR((
        FIELD(n)
    ));
};

REGISTER(test);

void test_gigabase () {
	dbDatabase db;
	if( db.open("/data/data/net.afpro.test.ndk/database") )
		d("Open database ok\n");
	else {
		d("Open database fail\n");
		return;
	}

	test t;
	t.n = 10;
	db.insert(t);

	dbCursor<test> tc(&db);
	tc.select();
	if( tc.first() ) do {
		d( tc.get()->n );
	} while( tc.next() );
}

bool reg(JNIEnv *env) {
	test_gigabase();
	return true;
}

extern "C"
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
	return AFcoder::JNI::JNI_OnLoad(vm, JNI_VERSION_1_4, reg);
}
